<script setup>
import dayjs from 'dayjs';
definePageMeta({
	layout: "flat",
})
const urlHome = useUrl();
const fileHome = fileUrl();
const pend = ref(false);
const docReport = ref([]);
const techReport = ref([]);
const litReport = ref([]);
const polReport = ref([]);
const cadcamReport = ref([]);
const zpTechReport = ref([]);
const zpPolReport = ref([]);
const zpLitReport = ref([]);
const zpCadcamReport = ref([]);
const isOpen = ref(false);
const naryadsModal = ref([]);
const podrSelect = ref(0);
const selectProfile = ref(0)
const selectPeriodID = ref(0)
const sumItog = ref(0);
const zarplata = ref(false);
const xlsxFile = ref(null);

const { data: periods } = await useFetch(`${urlHome.value}lab/period_date_dj/`)

const selectPeriod = computed(() => periods.value.find((element) => element.id == selectPeriodID.value))

async function dataFetch() {
	pend.value = true;
	let formData = new FormData();
	formData.append('dn_lg', dayjs(selectPeriod.value.dn_lg).format('YYYY-MM-DD'));
	formData.append('dk_lg', dayjs(selectPeriod.value.dk_lg).format('YYYY-MM-DD'));
	formData.append('dn_pl', dayjs(selectPeriod.value.dn_pl).format('YYYY-MM-DD'));
	formData.append('dk_pl', dayjs(selectPeriod.value.dk_pl).format('YYYY-MM-DD'));
	formData.append('year', selectPeriod.value.years);
	formData.append('month', selectPeriod.value.months);
	formData.append('podr', podrSelect.value);
	formData.append('profile', selectProfile.value);
	console.log("profile: ", selectProfile.value)
	const response = await $fetch(`${urlHome.value}lab/buh_zp/`, {
		method: 'POST',
		body: formData
	})
	if (response.ok) {
		docReport.value = response.docs
		techReport.value = response.techs
		litReport.value = response.lits
		polReport.value = response.pols
		cadcamReport.value = response.cadcams
		zpTechReport.value = response.zp_techs
		zpPolReport.value = response.zp_pols
		zpLitReport.value = response.zp_lits
		zpCadcamReport.value = response.zp_cadcams
		console.log(response.file)
		xlsxFile.value = response.file
	} else {
		alert("Ошибка загрузки отчета")
	}

	pend.value = false
}

async function openModal(mpp, spec, sumLab, sumUsl, zp) {
	const response = await $fetch(`${urlHome.value}lab/nar_for_check/`, {
		query: {
			mpp: mpp,
			spec: spec,
			profile: selectProfile.value,
			dn_lg: dayjs(selectPeriod.value.dn_lg).format('YYYY-MM-DD'),
			dk_lg: dayjs(selectPeriod.value.dk_lg).format('YYYY-MM-DD'),
			dn_pl: dayjs(selectPeriod.value.dn_pl).format('YYYY-MM-DD'),
			dk_pl: dayjs(selectPeriod.value.dk_pl).format('YYYY-MM-DD'),
			podr: podrSelect.value,
		}
	})
	if (response.ok) {
		if (zp === true) {
			zarplata.value = true
		} else if (zp === false)
			zarplata.value = false
		sumItog.value = sumLab + sumUsl
		naryadsModal.value = response.nars
		isOpen.value = true
	}
}

const naryadsSumm = computed(() => naryadsModal?.value?.reduce((sum, current) => sum + Number(current.stu), 0))

const podrList = [
	{ "lpu_name": "Выберите подразделение", "lpu_number": 0, "disabled": true },
	{ "lpu_name": "Все подразделения", "lpu_number": 1 },
	{ "lpu_name": "Поликлиинка №1", "lpu_number": 162 },
	{ "lpu_name": "Поликлиника №2", "lpu_number": 164 },
	{ "lpu_name": "Поликлиника №3", "lpu_number": 165 },
	{ "lpu_name": "Поликлиника №4", "lpu_number": 236 },
	{ "lpu_name": "Поликлиника №5", "lpu_number": 245 },
	{ "lpu_name": "Березовское стоматологическое отделение", "lpu_number": 3 },
	{ "lpu_name": "Стоматологическое отделение", "lpu_number": 243 },
	{ "lpu_name": "Топкинское стоматологическое отделение", "lpu_number": 28 },
	{ "lpu_name": "Яшкинское стоматологическое отделение", "lpu_number": 32 },
]

const profile = [
	{
		label: "Профиль",
		value: 0,
		disabled: true,
	},
	{
		label: 'Ортопедия',
		value: 2,
	}, {
		label: "Ортодонтия",
		value: 3
	}]

</script>

<template>
	<div>
		<h1>Отчет по доходам зуботехнической лаборатории</h1>
		<br>
		<div class="flex flex-row gap-2">
			<USelect v-model.number="podrSelect" :options="podrList" option-attribute="lpu_name"
				value-attribute="lpu_number" color="green" />
			<USelect v-model="selectProfile" :options="profile" option-attribute="label" value-attribute="value"
				color="green" />
			<USelect v-model="selectPeriodID" :options="periods" option-attribute="nmonth" value-attribute="id"
				color="green" />
			<UButton :disabled="pend || podrSelect < 1 || selectProfile < 1" label="Сформировать отчет по доходам"
				@click="dataFetch" />
			<div v-if="xlsxFile">
				<UButton :to="fileHome + xlsxFile" label="Скачать Excel">
				</UButton>
			</div>
			<UButton label="Меню" @click="navigateTo('/menu')" />
		</div>
		<div v-if="pend">
			<LoadFetchAnimation></LoadFetchAnimation>
		</div>

		<div v-if="docReport.length > 0">
			<BuhZpDoc :data="docReport" :label="`Врачи`" :openModal="openModal" :spec="`doc`" :zp="false" />
		</div>
		<div v-if="techReport.length > 0">
			<BuhZpSpec :data="techReport" :label="`Техники`" :openModal="openModal" :spec="`tech`" :zp="false" />
		</div>
		<div v-if="polReport.length > 0">
			<BuhZpSpec :data="polReport" :label="`Полировщики`" :openModal="openModal" :spec="`pol`" :zp="false" />
		</div>
		<div v-if="litReport.length > 0">
			<BuhZpSpec :data="litReport" :label="`Литейщики`" :openModal="openModal" :spec="`lit`" :zp="false" />
		</div>
		<div v-if="cadcamReport.length > 0">
			<BuhZpSpec :data="cadcamReport" :label="`Операторы Cad/Cam`" :openModal="openModal" :spec="`cadcam`"
				:zp="false" />
		</div>
		<div v-if="zpTechReport.length > 0">
			<BuhZpSpec :data="zpTechReport" :label="`Зарплата Зубные техники`" :openModal="openModal" :spec="`tech`"
				:zp="true" />
		</div>
		<div v-if="zpPolReport.length > 0">
			<BuhZpSpec :data="zpPolReport" :label="`Зарплата Полировщики`" :openModal="openModal" :spec="`pol`"
				:zp="true" />
		</div>
		<div v-if="zpLitReport.length > 0">
			<BuhZpSpec :data="zpLitReport" :label="`Зарплата Литейщики`" :openModal="openModal" :spec="`lit`"
				:zp="true" />
		</div>
		<div v-if="zpCadcamReport.length > 0">
			<BuhZpSpec :data="zpCadcamReport" :label="`Зарплата Операторы Cad/Cam`" :openModal="openModal"
				:spec="`cadcam`" :zp="true" />
		</div>
		<UModal v-model="isOpen" :ui="{ base: 'max-w-6xl', width: '' }">
			<UCard :ui="{ ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
				<template #header>
					<div class="flex place-items-end">
						<UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1"
							@click="isOpen = false" />
					</div>
				</template>
				<div class="font-bold">
					Итого {{ naryadsSumm.toLocaleString() }}р.</div>
				<div v-if="!zarplata">
					<div v-if="sumItog !== naryadsSumm" class="text-red-900 font-bold">
						!!! Внимание, не сходится сумма в нарядах и расчете зарплаты. Возможно расхождение в услугах
						нарядов.
					</div>
				</div>
				<table id="lgottable" class="text-center">
					<thead>
						<tr>
							<th>№п/п</th>
							<th>№ Наряда</th>
							<th>Дата откр.</th>
							<th>Дата закр.</th>
							<th>Пациент</th>
							<th>Доктор</th>
							<!-- <th>Техник</th> -->
							<th>Стоимость</th>
							<th>Подразделение</th>
							<th>Лаборатория</th>
							<!-- <th>ВТ</th> -->
						</tr>
					</thead>
					<tbody>
						<template v-for="( naryad, index ) in naryadsModal"
							class="flex gap-2 text-right font-mono place-content-evenly">
							<tr>
								<td class="font-mono">{{ index + 1 }}</td>
								<td class="font-mono">{{ naryad?.nkv }}</td>
								<td class="font-mono">{{ naryad?.dou ? dayjs(naryad.dou).format('DD.MM.YYYY') : "" }}
								</td>
								<td class="font-mono">{{ naryad?.dzr ? dayjs(naryad.dzr).format('DD.MM.YYYY') : "" }}
								</td>
								<td>{{ naryad.patientf }}</td>
								<td>{{ naryad.naryad_doc__user__fam }}</td>
								<td class="text-right font-mono"> {{ naryad?.stu.toLocaleString() }}</td>
								<td class="font-mono"> {{ naryad?.lpu__name_lpu }}</td>
								<td class="font-mono"> {{ naryad?.laboratory ? "ДА" : "Нет" }}</td>
							</tr>
						</template>
					</tbody>
				</table>
			</UCard>
		</UModal>
	</div>
</template>
<style scoped>
#lgottable {
	font-family: Arial, Helvetica, sans-serif;
	border-collapse: collapse;
	width: 100%;
}

#lgottable td,
#lgottable th {
	border: 1px solid #ddd;
	padding: 8px;
}

#lgottable tr:nth-child(even) {
	background-color: #f2f2f2;
}

#lgottable tr:hover {
	background-color: #ddd;
}

#lgottable th {
	padding-top: 12px;
	padding-bottom: 12px;
	text-align: center;
	background-color: #04AA6D;
	color: white;
}
</style>